import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import usage from "../utils/usage";

// 生产地址配置
let baseURL = "/api";

const instance = axios.create({
  baseURL,
  timeout: 1000 * 30,
  withCredentials: true,
  // headers: {
  //     'Content-Type': 'application/x-www-form-urlencoded'
  // }
});
let loadingInstance = null; // 加载中动画
// 请求拦截
instance.interceptors.request.use(
  (request) => {
    const match = request.url.match(/\/([^/]+)/)[1];
    const req = request;
    if(match == 'smart' || match === 'varokUrl'){ // 数据接口，提供数据登录token
      req.headers.authorization = usage.getToken();
    }else if(request.url.startsWith('/screen/openapi')){ // 视频接口，提供视频登录token
      if(!request.url.includes("getToken")){ // 登录接口不传递请求头
        let videoInfo =usage.getCache('videoInfo');
        req.headers.authorization = `${videoInfo.token_type} ${videoInfo.access_token}`
      }
    }else if(request.url.startsWith('/screen/smartRice')){ // 物联接口，使用物联token
      let videoInfo = usage.getCache('ioTToken').replace(/^"|"$/g, '');
      req.headers.authorization = `${videoInfo}`
    }
    
    loadingInstance = ElLoading.service({
      fullscreen: true,
      background: `rgba(0, 0, 0, 0)`,
      text: '加载中...'
    });
    return req;
  },
  (err) => {
    loadingInstance.close();
    ElMessage.warning("请求超时");
    return Promise.reject(err);
  }
);

// 响应拦截
instance.interceptors.response.use(
  (response) => {
    loadingInstance.close();
    const { data } = response;
    if (data && data.code == '200') {
      return data || true;
    } else if (data.code == 10001) {
      ElMessage.error("请重新登录");
      usage.logOut();
    } else {
      ElMessage.error(data.message || "系统错误");
      return false;
    }
  },
  (err) => {
    loadingInstance.close();
    ElMessage.error("服务错误");
    return Promise.reject(err);
  }
);

// get方法
const $get = (url, params) =>
  new Promise((resolve, reject) => {
    instance
      .get(url, {
        params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });

// post方法
const $post = (url, params) =>
  new Promise((resolve, reject) => {
    instance
      .post(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });

export { $get, $post, instance };
